package controllers;

import java.util.ArrayList;
import java.util.List;

import models.Course;
import models.CourseRequest;
import models.Student;
import play.mvc.Controller;
import play.mvc.With;

@With (Secure.class)
@Check ("ta")
public class CourseRequests extends Controller {
	public static void index() {
		render();
	}

	public static void list(long type, long courseId, long studentId) {
		List<CourseRequest> requests = null;
		List<Student> students = null;
		List<Course> courses = null;

		if (type == 1) {
			if (courseId == 0) {
				courses = Course.findAll();
			} else {
				requests = CourseRequest.find("byTutorial.course", Course.<Course> findById(courseId)).fetch();
			}
		} else if (type == 2) {
			if (studentId == 0) {
				students = Student.findAll();
			} else {
				requests = CourseRequest.find("byStudent", Student.<Student> findById(studentId)).fetch();
			}
		} else if (type == 3) {
			requests = CourseRequest.findAll();
		}

		render(requests, students, courses);
	}

	public static void process(String url) {
		List<Long> accept = new ArrayList<Long>();
		List<Long> decline = new ArrayList<Long>();

		for (String key : params.all().keySet()) {
			if (!key.startsWith("r_"))
				continue;
			String[] k = key.split("_");
			int val = Integer.parseInt(params.all().get(key)[0]);
			if (val == 1) {
				accept.add(Long.parseLong(k[1]));
			} else if (val == 2) {
				decline.add(Long.parseLong(k[1]));
			}
		}
		int count = 0;
		for (long i : accept) {
			CourseRequest req = CourseRequest.findById(i);
			req.tutorial.students.add(req.student);
			req.tutorial.save();
			req.delete();
			count++;
		}

		for (long i : decline) {
			CourseRequest req = CourseRequest.findById(i);
			req.delete();
			count++;
		}

		if (count > 0) {
			flash.success("Successfully processed " + count + " requests");
		} else {
			flash.error("Did not process any requests");
		}

		redirect(url);
	}
}